package com.huluobo.a2111douyindemo.adapter;

import android.graphics.Color;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.huluobo.a2111douyindemo.R;
import com.huluobo.a2111douyindemo.live.MessageEntity;

import java.util.List;

/**
 * 带富文本编辑器的adapter
 * Created by LC on 2024/3/8.
 */
public class MessageAdapter extends BaseQuickAdapter<MessageEntity, BaseViewHolder> {

    private int[] resIds = {
            R.drawable.chat_bg_0,
            R.drawable.chat_bg_1,
            R.drawable.chat_bg_2,
            R.drawable.chat_bg_3,
            R.drawable.chat_bg_4,
            R.drawable.chat_bg_3,
            R.drawable.chat_bg_2,
            R.drawable.chat_bg_1,
            R.drawable.chat_bg_3,
            R.drawable.chat_bg_0,
            R.drawable.chat_bg_1,
            R.drawable.chat_bg_2,
            R.drawable.chat_bg_3,
            R.drawable.chat_bg_4,
            R.drawable.chat_bg_3,
            R.drawable.chat_bg_2,
            R.drawable.chat_bg_1,
            R.drawable.chat_bg_3
    };

    public MessageAdapter(@Nullable List<MessageEntity> data) {
        super(R.layout.item_chat_room_msg_layout, data);
    }

    @Override
    protected void convert(@NonNull BaseViewHolder baseViewHolder, MessageEntity messageEntity) {
        //设置聊天文字的背景
        int index = (int) (resIds.length % (Math.random() * 10));
        //通过随机数给聊天背景设置shape
        baseViewHolder.setBackgroundResource(R.id.item_chat_room_ll, resIds[index]);

        //消息内容:  <span color = red>张三:</span><span color=yellow>发送了一条消息</span>
        // 这条消息可以通过富本文编辑器标签包裹文字实现设置颜色
        String msg = messageEntity.getName() + ":" + messageEntity.getMessage();

        //构建一个富文本编辑器
        SpannableStringBuilder builder = new SpannableStringBuilder(msg);

        //定义2个颜色
        ForegroundColorSpan blue = new ForegroundColorSpan(Color.BLUE);
        ForegroundColorSpan yellow = new ForegroundColorSpan(Color.YELLOW);

        //拼接标签 SPAN_INCLUSIVE_INCLUSIVE 标签是否包含最后一个元素
        builder.setSpan(blue, 0, messageEntity.getName().length() + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        builder.setSpan(yellow, messageEntity.getName().length() + 1, msg.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

        baseViewHolder.setText(R.id.item_chat_room_content_tv, builder);
    }
}
